﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Core.BusinessLogic.Interfaces;
using Core.Interfaces;
using Core.DataAccess.IRepositories;
using Core.Common;
using Core.DataAccess;
using System.Web;
using System.IO;
using System.Drawing;
using File = Core.DataAccess.File;

namespace Core.BusinessLogic
{
    [Export(typeof(IUploadService))]
    public class UploadService : IUploadService
    {
        public string ImageFolder = "";
        Dictionary<string, int> sizesToMake = new Dictionary<string, int>();
        private int sizeTiny = 50;
        private int sizeSmall = 200;
        private int sizeMedium = 500;
        private int sizeLarge = 1000;
        int NewWidth = 0;
        int NewHeight = 0;

        string saveToFolder = "";

        [Import]
        public IWebContext _webContext;
        [Import]
        private IFileRepository _fileRepository;
        [Import]
        private IAccountRepository _accountRepository;
        [Import]
        private IFolderRepository _folderRepository;
        [Import]
        private IFileFolderRepository _fileFolderRepository;
        [Import]
        private IFolderImgCoverRepository _folderImgCoverRepository;
        [Import]
        private IFileImgCoverRepository _fileImgCoverRepository;

        public UploadService()
        {
            MEFManager.Compose(this);
        }

        public List<long> UploadPhotos(Guid guidName, int FileTypeID, int AccountID, System.Web.HttpFileCollection Files, long AlbumID, string imgCover)
        {                        
            List<long> result = new List<long>();
            Guid folderID = Guid.NewGuid();
            Guid folderIDImgCover = Guid.NewGuid();
            if (Files.Count > 0 && imgCover != "1")
                folderID = _folderRepository.SaveFolder(new Folder { FolderID = folderID, AccountID = AccountID, CreateDate = DateTime.Now, Name = string.Empty, IsPublicResource = true, Description = string.Empty, FolderTypeID = (int)1 });
            else if (Files.Count > 0 && imgCover == "1")
                folderIDImgCover = _folderImgCoverRepository.SaveFolderImgCover(new FolderImgCover { FolderID = folderIDImgCover, CreateDate = DateTime.Now, AccountID = AccountID, FolderTypeID = (int)1 });
            saveToFolder = _webContext.FilePath + "Files\\";
            if (FileTypeID == 1)
            {
                sizesToMake.Add("T", sizeTiny);
                sizesToMake.Add("S", sizeSmall);
                sizesToMake.Add("M", sizeMedium);
                sizesToMake.Add("L", sizeLarge);
            }
            switch (FileTypeID)
            {
                case 1:
                    saveToFolder += "Photos\\";
                    break;

                case 2:
                    saveToFolder += "Videos\\";
                    break;

                case 3:
                    saveToFolder += "Audios\\";
                    break;
            }            
            //saveToFolder += DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "\\";
            if (!Directory.Exists(saveToFolder))
                Directory.CreateDirectory(saveToFolder);
            Account account = _accountRepository.GetAccountByID(AccountID);                        
            for (int i = 0; i < Files.Count; i++)
            {
                HttpPostedFile F = Files[i];
                if (Files[i] != null && F.ContentLength > 0)
                {                    
                    string uploadedFileName = F.FileName.Substring(F.FileName.LastIndexOf("\\") + 1);
                    string extension = uploadedFileName.Substring(uploadedFileName.LastIndexOf(".") + 1);                    
                    string fullFileName = saveToFolder + guidName.ToString() + "__O." + extension;
                    bool goodFile = true;

                    //create the file
                    File file = new File();
                    FileImgCover fileImgCover = new FileImgCover();

                    #region "Determine file type"
                    switch (FileTypeID.ToString())
                    {
                        case "1":
                            file.FileSystemFolderID = (int)FileSystemFolder.Paths.Photos;
                            fileImgCover.FileSystemFolderID = (int)FileSystemFolder.Paths.Photos;
                            switch (extension.ToLower())
                            {
                                case "jpg":
                                    file.FileTypeID = (int)File.Types.JPG;
                                    fileImgCover.FileTypeID = (int)File.Types.JPG;
                                    break;
                                case "gif":
                                    file.FileTypeID = (int)File.Types.GIF;
                                    fileImgCover.FileTypeID = (int)File.Types.GIF;
                                    break;
                                case "jpeg":
                                    file.FileTypeID = (int)File.Types.JPEG;
                                    fileImgCover.FileTypeID = (int)File.Types.JPEG;
                                    break;
                                case "png":
                                    file.FileTypeID = (int)File.Types.PNG;
                                    fileImgCover.FileTypeID = (int)File.Types.PNG;
                                    break;
                                default:
                                    goodFile = false;
                                    break;
                            }
                            break;

                        case "2":
                            file.FileSystemFolderID = (int)FileSystemFolder.Paths.Videos;
                            switch (extension.ToLower())
                            {
                                case "wmv":
                                    file.FileTypeID = (int)File.Types.WMV;
                                    break;
                                case "flv":
                                    file.FileTypeID = (int)File.Types.FLV;
                                    break;
                                case "swf":
                                    file.FileTypeID = (int)File.Types.SWF;
                                    break;
                                case "mp4":
                                    file.FileTypeID = (int)File.Types.MP4;
                                    break;
                                case "ogg":
                                    file.FileTypeID = (int)File.Types.OGG;
                                    break;
                                case "webm":
                                    file.FileTypeID = (int)File.Types.WEBM;
                                    break;
                                default:
                                    goodFile = false;
                                    break;
                            }
                            break;

                        case "3":
                            file.FileSystemFolderID = (int)FileSystemFolder.Paths.Audios;
                            switch (extension.ToLower())
                            {
                                case "wav":
                                    file.FileTypeID = (int)File.Types.WAV;
                                    break;
                                case "mp3":
                                    file.FileTypeID = (int)File.Types.MP3;
                                    break;
                                //case "flv":
                                //    file.FileTypeID = (int)File.Types.FLV;
                                //    break;
                                default:
                                    goodFile = false;
                                    break;
                            }
                            break;
                    }
                    #endregion                    

                    if (imgCover == "1")
                    {
                        fileImgCover.Size = F.ContentLength;
                        fileImgCover.AccountID = account.AccountID;
                        fileImgCover.DefaultFolderID = folderID;
                        fileImgCover.FileName = uploadedFileName;
                        fileImgCover.FileSystemName = guidName;
                        fileImgCover.Description = "";
                    }
                    else
                    {
                        file.Size = F.ContentLength;
                        file.AccountID = account.AccountID;
                        file.DefaultFolderID = folderID;
                        file.FileName = uploadedFileName;
                        file.FileSystemName = guidName;
                        file.Description = "";
                        file.IsPublicResource = false;
                    }
                    if (goodFile)
                    {                                                
                        if (imgCover == "1")
                            result.Add(_fileImgCoverRepository.SaveFileImgCover(fileImgCover));
                        else
                            result.Add(_fileRepository.SaveFile(file));
                        if(FileTypeID != 2)
                            F.SaveAs(fullFileName);
                        else if (FileTypeID == 2)
                        {
                            fullFileName = saveToFolder + guidName.ToString() + "__O.";
                            F.SaveAs(fullFileName + "mp4");
                            //F.SaveAs(fullFileName + "ogg");
                            //F.SaveAs(fullFileName + "webm");
                            //F.SaveAs(fullFileName + "swf");
                        }
                        if (FileTypeID == ((int)Folder.Type.Photo))
                        {
                            Resize(F, saveToFolder, guidName, extension);
                        }
                    }
                }
            }
            _fileFolderRepository.SaveFileFolder(result, folderID, AccountID);
            return result;
        }
        
        public void Resize(HttpPostedFile F, string SaveToFolder, Guid SystemFileNamePrefix, string Extension)
        {
            //Makes all the different sizes in the sizesToMake collection
            foreach (KeyValuePair<string, int> pair in sizesToMake)
            {
                using (System.Drawing.Image image = System.Drawing.Image.FromStream(F.InputStream))
                //determine the thumbnail sizes
                using (Bitmap bitmap = new Bitmap(image))
                {
                    decimal Ratio;
                    if (bitmap.Width > bitmap.Height)
                    {
                        Ratio = (decimal)pair.Value / bitmap.Width;
                        NewWidth = pair.Value;
                        decimal Temp = bitmap.Height * Ratio;
                        NewHeight = (int)Temp;
                    }
                    else
                    {
                        Ratio = (decimal)pair.Value / bitmap.Height;
                        NewHeight = pair.Value;
                        decimal Temp = bitmap.Width * Ratio;
                        NewWidth = (int)Temp;
                    }
                }

                using (System.Drawing.Image image = System.Drawing.Image.FromStream(F.InputStream))
                using (Bitmap bitmap = new Bitmap(image, NewWidth, NewHeight))
                {
                    bitmap.Save(SaveToFolder + "/" + SystemFileNamePrefix.ToString() + "__" + pair.Key + "." + Extension, image.RawFormat);
                }
            }
        }        
    }
}
